package com.hwpt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hwpt.constant.ExceptionMessageConstant;
import com.hwpt.dto.admin.AdminDTO;
import com.hwpt.entity.Admin;
import com.hwpt.exception.AuthException;
import com.hwpt.mapper.AdminMapper;
import com.hwpt.service.AdminAuthService;
import com.hwpt.utils.SCryptUtil;
import com.hwpt.vo.admin.AdminLoginVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


@Service
@RequiredArgsConstructor
@Slf4j
public class AdminAuthServiceImpl implements AdminAuthService {

    private final AdminMapper adminMapper;
    private final SCryptUtil sCryptUtil;

    /**
     * 管理员登录
     */
    @Override
    public AdminLoginVo login(AdminDTO adminDTO) {
        String username = adminDTO.getUsername();
        String password = adminDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        LambdaQueryWrapper<Admin> query = new LambdaQueryWrapper<>();
        query.eq(Admin::getAdminUsername, username);
        Admin admin = adminMapper.selectOne(query);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (admin == null) {
            //账号不存在
            throw new AuthException(ExceptionMessageConstant.ACCOUNT_NOT_EXIST);
        }

        //SCryptUtil算法解密
        if(!sCryptUtil.verify(password, admin.getAdminPassword())){
            //密码错误
            throw new AuthException(ExceptionMessageConstant.LOGIN_PASSWORD_ERROR);
        }
        AdminLoginVo adminLoginVO = new AdminLoginVo();
        BeanUtils.copyProperties(admin, adminLoginVO);
        //3、返回实体对象
        return adminLoginVO;
    }

}
